#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName  :models.py
# @Time      :2021/04/06 14:16:37
# @Author    :Raink
# orm  城市信息表，感染数据表
# 02


# 字段类型
from sqlalchemy import Column, String, Integer, BigInteger, Date, DateTime, ForeignKey, func
from sqlalchemy.orm import relationship  # 关系型字段

from .database import Base

class City(Base):
    __tablename__ = 'city'  # 表名
    # primary_key 主键， autoincrement自增长
    id = Column(Integer, primary_key=True, index=True, autoincrement=True)
    # unique必须唯一， nullable 不可为空
    province = Column(String(100), unique=True, nullable=False, comment="省/直辖市")
    country = Column(String(100), nullable=False, comment='国家')
    country_code = Column(String(100), nullable=False, comment='国家代码')
    country_population = Column(BigInteger, nullable=False, comment='国家人口')
    # Data是关联的类名，back_populates 来指定反向访问的属性名
    data = relationship('Data', back_populates='city')

    # 创建或更新时插入当前时间
    created_at = Column(DateTime, server_default=func.now(), comment='创建时间')
    updated_at = Column(DateTime, server_default=func.now(), onupdate=func.now(), comment='更新时间')
    
    # 1.4+版本已经弃用 extension, order_by,两个参数  
    # The mapper.order_by parameter is deprecated, and will be removed in a future release. Use Query.order_by() to determine the ordering of a result set.
    # __mapper_args__ = {"order_by": country_code}  # 默认是正序，倒序加上.desc()->  country_code.desc()

    def __repr__(self) -> str:
        return f'{self.country}_{self.provice}'


class Data(Base):
    __tablename__ = 'data'
    id = Column(Integer, primary_key=True, index=True, autoincrement=True)
    # 外键，关联到上一张表，
    # 表名.字段名，而不是类名.属性名
    city_id = Column(Integer, ForeignKey("city.id"))  
    date = Column(Date ,nullable=False, comment='数据日期')
    confirmed = Column(BigInteger, default=0, nullable=False, comment="确诊数量")
    deaths = Column(BigInteger, default=0, nullable=False, comment="死亡人数")
    recovered = Column(BigInteger, default=0, nullable=False, comment="治愈人数")
    city = relationship('City', back_populates='data')

    created_at = Column(DateTime, server_default=func.now(), comment='创建时间')
    updated_at = Column(DateTime, server_default=func.now(), onupdate=func.now(), comment='更新时间')

    # 1.4+版本已经弃用 extension, order_by,两个参数
    # The mapper.order_by parameter is deprecated, and will be removed in a future release. Use Query.order_by() to determine the ordering of a result set.
    # __mapper_args__ = {"order_by":date.desc()}  # 默认是正序，倒序加上.desc()

    def __repr__(self) -> str:
        return f'{repr(self.date)}：确诊{self.confirmed} 例'

